let fs = require('fs');

let data = fs.readFileSync('./tv/fm.js');

//取eval中的内容
data = data.toString().match(/(?<=eval\(')([.\s\S]+?\)\);)(?=('\)))/g)[0];
//处理\'
data = data.replace(/\\\'/g, `\'`);
data = data.replace(/\\\\/g, `\\`);
//获取所有加密字串
let varStr = data.match(/[a-zA-Z0-9]+='[.\s\S]*?'(?=,|;)/ig);
let vars = {};
varStr.forEach((a) => {
    //取第一个等号下标
    let index=a.indexOf('=');
    let vr1=a.substring(0,index),
    vr2=a.substr(index+1);

    if (vr1) {
        if (vr2.match(/'/g).length >= 2) {
            vr2 =vr2.substring(1, vr2.length - 1);
        }
        vars[vr1.trim()] = vr2;
    }
});
//解密方法
function Q0OOOooQ(str, len) {
    let ret = '';
    for (let i = 0; i < str.length; i++) ret += String.fromCharCode(((str.charCodeAt(i) - 32 ^ 31 & i) + 95 - len) % 95 + 30);
    return ret;
}
//临时数组存放
let tempList=[];
//获取等式循环解密进行循环解密
data.match(/[a-zA-Z0-9]+\([a-zA-Z0-9]+,[0-9]+\)/ig).forEach((code)=>{
    let key=code;
    //取出name
    let varName=key.match(/(?<=(\())[0-9a-z-A-Z]+?(?=(,[\d]+\)))/g)[0];
    if(vars[varName]){
        code=code.replace(varName,encodeURIComponent('\''+vars[varName]+'\''));
        code=decodeURIComponent(code);
        let val=eval('('+code+')');
        //替换全部
        data=data.replace(key,JSON.stringify(val));
        tempList.push(varName);
    }else{
        console.log('----');
        console.log(vars[varName]);
        console.log(code);
        console.log(varName);
    }
});
//删除完成的name
tempList.forEach((key)=>{
    delete vars[key];
});
//处理剩余未解密变量
Object.keys(vars).forEach((key)=>{
    if(key && vars[key]){
        let val=JSON.stringify(vars[key]);
        //取()中的变量
        data=data.replace(new RegExp('\\('+key+'\\)','g'),'('+val+')');
        //处理[]中的变量
        data=data.replace(new RegExp('\\['+key+'\\]','g'),'['+val+']');
        //处理=
        data=data.replace(new RegExp('='+key,'g'),'='+val);
        //全部替换
        data=data.replace(new RegExp(key+'(?!=)','g'),val);
    }
});
//再次处理，将["a"]变成.a
data=data.replace(/\["([a-zA-Z_]+)"\]/ig,'.$1');
//------------------------字符串解密完成--------------------------
//方法处理


//保存文件
fs.writeFileSync('./out.js',data);
